package com.wangsd.common.task;


import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.wangsd.common.component.WxApiV3CouponService;
import com.wangsd.common.component.WxpayService;
import com.wangsd.common.utils.OssFileUtils;
import com.wangsd.web.shop.entity.CouponOrder;
import com.wangsd.web.shop.entity.Merchant;
import com.wangsd.web.shop.entity.Trade;
import com.wangsd.web.shop.service.CouponOrderService;
import com.wangsd.web.shop.service.CouponService;
import com.wangsd.web.shop.service.MerchantService;
import com.wangsd.web.shop.service.TradeService;
import com.wangsd.web.sys.entity.SysCompany;
import com.wangsd.web.sys.entity.UploadFile;
import com.wangsd.web.sys.service.SysCompanyService;
import com.wangsd.web.sys.service.UploadFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class MyTask {
    @Autowired
    UploadFileService uploadFileService;
    @Autowired
    CouponOrderService couponOrderService;
    @Autowired
    CouponService couponService;
    @Autowired
    TradeService tradeService;
    @Autowired
    SysCompanyService companyService;
    @Autowired
    MerchantService merchantService;

    @Scheduled(fixedRate = 30000) //半分钟分钟执行一次
    public void updateTrade() {

        log.info("#########定时删除未支付的优惠券订单#########");
        couponOrderService.deleteByStatus();

        log.info("#########定时删除未支付的交易订单#########");
        tradeService.deleteByStatus();

    }

//    @Scheduled(fixedRate = 3600000) //一小时执行一次
    @Scheduled(cron = "0 0 1 * * ?") //每天晚上1点执行
    public void updateCouponOrderStatus() {
        log.info("#########定时任务开始执行#########");

        log.info("#########定时删除多余文件#########");
        List<UploadFile> list = uploadFileService.selectByDelete();
        for (UploadFile file: list) {
            OssFileUtils.deleteFile(file.getFilename());
            uploadFileService.deleteByFileName(file.getFilename());
        }

        log.info("#########定时更新已过期的优惠券订单（并退款）#########");
        List<CouponOrder> coList = couponOrderService.selectByGuoqi();
        List<Long> ids = coList.stream().map(CouponOrder::getId).collect(Collectors.toList());
        //更新过期字段
        if (ids.size() > 0) {
            couponOrderService.updateByGuoqi(ids);
        }
        log.debug(coList.size() + "");
        //退款
        for (CouponOrder couponOrder : coList) {
            log.debug(couponOrder.getCouponCode());
            if (couponOrder.getIsRefund()) {
                Trade trade = tradeService.selectByOutTradeNo(couponOrder.getOutTradeNo());
                if (trade != null && trade.getStatus() == 1 && StringUtils.isNotBlank(trade.getTransactionId())) {
                    String[] codes = couponOrder.getParentCode().split("-");
                    SysCompany company = companyService.selectByCode(codes[0]);
                    Merchant merchant = merchantService.selectByCode(couponOrder.getParentCode());
                    WxpayService wxpayService = new WxpayService(company, merchant.getSubMchId(), merchant.getSubAppid());
                    //发生异常继续执行
                    try {
                        WxPayRefundResult result = wxpayService.refund(trade.getTransactionId(), trade.getPrice(), trade.getCashFee());
                        String returnCode = result.getReturnCode();
                        String resultCode = result.getResultCode();
                        if (WxPayConstants.ResultCode.SUCCESS.equals(returnCode)//执行结果成功
                                && WxPayConstants.ResultCode.SUCCESS.equals(resultCode)) {
                            trade.setStatus(2);
                            trade.setOutRefundNo(result.getOutRefundNo());
                            tradeService.update(trade);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        }

        log.info("#########定时任务执行结束#########");
    }
}
